package com.mzj.saas.mservice.department.repository;

import com.mzj.saas.mservice.department.entity.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface DepartmentRepository extends PagingAndSortingRepository<Department, Long>, JpaSpecificationExecutor<Department>, JpaRepository<Department, Long> {
    List<Department> findAllByParentIdOrderBySortbyDesc(Long parentId);

    Department findAllByParentIdAndName(Long parentId, String name);
    Department findAllByIdAndStatus(Long id, Integer status);


    List<Department> findAll();

    List<Department> findByParentId(Long parentId);

    @Transactional
    void deleteByParentId(Long parentId);

    List<Department> findByIdInAndName(List<Long> ids, String name);

    List<Department> findByIdIn(List<Long> ids);

    List<Department> findByIdInOrderByLevel(List<Long> ids);

    List<Department> findByIdInAndNameLikeOrderBySortbyDesc(List<Long> ids, String name);

    boolean existsByParentId(Long parentId);

    @Query(nativeQuery = true, value = "SELECT MAX(id) FROM `saas_department` WHERE parent_id = :parentId AND code IS NOT NULL")
    Long findByParentIdMaxId(@Param("parentId") Long parentId);


    Department findByNameAndParentId(String depName, Long parentId);
}
